﻿# coding: utf-8

module FindAndClean

  # Finds all Ruby source files under the current or other supplied
  # directory. A Ruby source file is defined as a file with the `.rb`
  # extension or a file with no extension that has a ruby shebang line
  # as its first line.
  # @param root Root directory under which to search for 
  # ruby source files
  # @return [Array] Array of filenames
  def ruby_files(root = Dir.pwd)
    files = Dir.open(root).reject { |file| FileTest.directory? file }
    rb_files = []
    rb_files << files.select { |file| File.extname(file) == '.rb' }
    rb_files << files.select do |file|
      File.extname(file) == '' &&
      File.open(file) { |f| f.readline } =~ /#!.*ruby/
    end
    rb_files.flatten.sort
  end
  
  def all_files(root = Dir.pwd)
    files = Dir.open(root).reject { |file| FileTest.directory? file }
    files_found = files.select do |file| 
      file !=~ /^\./ 
    end
    files_found.sort
  end

  def clean_all_filenames(root = Dir.pwd)
    renamed = []
    self.all_files(root).each do |file|
      new_name = file.downcase.gsub(/\s+/, '_')
      File.rename(file, new_name)
      puts "#{file} => #{new_name}"
      renamed << new_name
    end
    renamed.count
  end

  def get_pwd
    Dir.pwd
  end

  def get_list
    out = ""
    all_files.each do |file|
      out << "- " << File.absolute_path(file)
      out << " | " << File.atime(file).to_s
      out << " | " << File.size(file).to_s
      out << "\n"
    end
    puts out
  end

end #FindAndClean

